//! By convention, main.zig is where your main function lives in the case that
//! you are building an executable. If you are making a library, the convention
//! is to delete this file and start with root.zig instead.
const std = @import("std");
const lib = @import("zigdemo_lib");
const httpz = @import("httpz");
pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    var server = try httpz.Server(void).init(allocator, .{ .port = 5882 }, {});
    defer {
        server.stop();
        server.deinit();
    }

    var router = try server.router(.{});

    router.get("/:id", getUser, .{});

    try server.listen();
}

fn getUser(req: *httpz.Request, res: *httpz.Response) !void {
    const allocator = std.heap.page_allocator;
    res.status = 200;
    try res.json(.{ .id = req.param("id").?, .name = "Teg" }, .{});
    const timstamp = std.time.timestamp();
    const format = "{d:0>4}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2}:{d:0>2}";
    const ft = try dateFormat(allocator, timstamp, format);
    //const ft = std.time.epoch.EpochSeconds.getDaySeconds(std.time.epoch.EpochSeconds);
    std.debug.print("{s} /:id -> {s} \n", .{ ft, req.param("id").? });
}

fn isLeapYear(year: i64) bool {
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0;
}
fn dateFormat(allocator: std.mem.Allocator, timstamp: i64, format: []const u8) anyerror![]u8 {
    const seconds = @divTrunc(timstamp, 1);

    var year: i64 = 1970;
    var days: i64 = @divTrunc(seconds, 86400);
    while (days >= 365 and isLeapYear(year)) {
        days -= 365 + isLeapYear(year);
        year += 1;
    }

    const months = [_]u32{ 31, 28 + isLeapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    var month: u32 = 0;
    while (days >= months[month]) {
        days -= months[month];
        month += 1;
    }

    const day = days + 1;

    const hour = (seconds % 86400) / 3600;
    const minute = (seconds % 3600) / 60;
    const second = seconds % 60;

    return std.fmt.allocPrint(allocator, format, .{
        year,
        month + 1,
        day,
        hour,
        minute,
        second,
    });
}
